﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.InteropServices;
using System.Diagnostics;
using Microsoft.Win32;
using System.Threading;

namespace KeyCtrl
{
    public class Controller
    {
        private Boolean _showing;
        private HotKeyFilter _hotKeyFilter;
        private KeyDaemon _daemon;
        private ShortcutForm _view;
        private EnvDTE.DTE _dte;

        public delegate void InvokeActivate();

        public Controller(EnvDTE.DTE dte)
        {
            _dte = dte;

            Logger.Log("Starting controller constructor");
            _showing = false;

            _daemon = new KeyDaemon();
            _hotKeyFilter = new HotKeyFilter(AppConfig.HideCombo(), _daemon, new EventHandler(Hide));
            Logger.Log("HotKeyFilter constructed");
            _daemon.StartLogging();
            Logger.Log("Hot key listener started");

            _view = new ShortcutForm(this);
        }

        private void SettingsLink_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) {ShowSettingsImpl();}
        
        private void AboutImpl()
        {
            Logger.Log("About box opened");
                new AboutBox().Show();
            Logger.Log("About box closed");
        }

        private void DieImpl() {}

        private void ShowSettingsImpl()
        {
            /*
            bool wasShowing = _showing;
            Logger.Log("Settings dialog opened");
            
            HideImpl();
            _daemon.StopLogging();
            new ConfigForm().ShowDialog();
            _hotKeyFilter.ActivationCombo = AppConfig.ActivateCombo;
            _hotKeyFilter.Combo = AppConfig.HideCombo;
            _daemon.StartLogging();
            if (wasShowing)
                ActivateImpl();
            
            Logger.Log("Settings dialog closed");
            */
        }

        public void Activate(object sender, System.EventArgs e)
        {
            Logger.Log("Activate Combo was pressed");
            ActivateImpl();
        }

        public void Hide(object sender, System.EventArgs e)
        {
            Logger.Log("Hide Combo was pressed");
            HideImpl();
        }

        public void ActivateImpl()
        {
            if (_showing || _dte.ActiveDocument == null || _dte.ActiveDocument.Language == null)
                return;

            _showing = true;
            _view.Show(_dte.ActiveDocument.Language);
            
            Logger.Log("Window activated");
        }


        public void HideImpl()
        {
            if (_showing)
            {
                _showing = false;
                _view.Hide();
                Logger.Log("Window hided");
            }
        }
    }
}
